import can

def openPCAN():
    can0 = can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=500000)
    return can0
def sendCAN(can0, id, data):
    msg = can.Message(arbitration_id=id, data=data, is_extended_id=False)
    can0.send(msg)
    return

def read_pcan_data():
    try:
        # 初始化 PCAN 通道
        bus =openPCAN()
        print("PCAN 通道初始化成功")

        while True:
            # 读取 CAN 消息
            message = bus.recv(timeout=1.0)  # 超时时间设置为 1 秒
            if message is not None:
                print(f"收到 CAN 消息:")
                print(f"  仲裁 ID: {hex(message.arbitration_id)}")
                print(f"  数据: {message.data}")
            else:
                print("在 1 秒内未收到消息，继续等待...")

    except can.CanError as e:
        print(f"PCAN 通道初始化或读取数据时出错: {e}")
    finally:
        # 关闭 CAN 总线
        if 'bus' in locals():
            bus.shutdown()
            print("PCAN 通道已关闭")

if __name__ == "__main__":
    read_pcan_data()